/*-----------------------------------------------------------------------------
* @Description:     人员基本信息列表
* @Version:         1.0.0
* @author:          xuexy(915585955@qq.com)
* @date             2017.11.07
* ==NOTES:=============================================
* v1.0.0(2017.11.07):
     初始生成
* ---------------------------------------------------------------------------*/
$(function(){
	/**
     * 初始化提示信息、验证表单
     */
    Pagination(1);
    formValidatorEditForm();
    formValidatorAddForm();
    //多选下拉框绑定
    $('#addGrade').multiselect();
    $('#editGrade').multiselect();
    $('#editCourse').multiselect();
    $('#addCourse').multiselect();

    
 
    // 全选 
    var subChk = $("input[name='subChk']");
    $(".J_allChk").click(function() { 
        $("input[name='subChk']").prop("checked",this.checked); 
    }); 
    // 单选 
    $(document).on('click',"input[name='subChk']",function() { 
        $(".J_allChk").prop("checked", $("input[name='subChk']").length == $("input[name='subChk']").filter(":checked").length ? true:false); 
    });

     /**
     * 列表点击修改事件
     * @param  {[type]} ){                     }
     * @return {[type]}     [description]
     */
    $(document).on('click', '.J_modify', function(e){
        modifyInfo(e);
        $("#editDialog").modal('show');
        changeEditRole();
    });

    /**
     * 列表点击新增事件
     * @param  {[type]} ){                     }
     * @return {[type]}     [description]
     */
    $(document).on('click', '.J_addInfo', function(){
        $("#addDialog").modal('show');
        changeAddRole();
    });

    /**
     * 新增对话框切换角色选项事件
     * @param  {[type]} ){                     }
     * @return {[type]}     [description]
     */
    $('.J_addRole').change(function(){
        changeAddRole();
        $('#addGrade').val('').multiselect("refresh");
        $('#addCourse').val('').multiselect("refresh");
        
    });

    /**
     * 修改对话框切换角色选项事件
     * @param  {[type]} ){                     }
     * @return {[type]}     [description]
     */
    $('.J_editRole').change(function(){
        changeEditRole();
        $('#editGrade').val('').multiselect("refresh");
        $('#editCourse').val('').multiselect("refresh");
    });

     /**
     * 列表点击搜索事件
     * @param  {[type]} ){                     }
     * @return {[type]}     [description]
     */
    $(".J_search").click(function(){
        var
            form = $(".J_searchForm").serializeObject();

        Pagination(1, form);
    });


    /**
     * 点击批量删除按钮
     * @param  {[type]} ){                     }
     * @return {[type]}     [description]
     */
    $(".J_allDel").click(function() { 
        delAll();
    }); 


    /**
     * 分页
     */
    $('#pageLimit').bootstrapPaginator({
        //currentPage: 3,
       /* totalPages: $('.pageDataCount').val(),*/
        size: "small",
        bootstrapMajorVersion: 3,
        alignment: "right",
        numberOfPages: 5,
        itemTexts: function (type, page, current) {
            switch (type) {
                case "first": return "首页";
                case "prev": return "<";
                case "next": return ">";
                case "last": return "末页";
                case "page": return page;
            }
        },
        onPageClicked: function (event, originalEvent, type, page) {
            var
                form = $(".J_searchForm").serializeObject();

            Pagination(page, form);  
        }
    });
    /**
     * 分页刷数据
     */
    function Pagination(page, extraData){

        var
            currentPage = page,            
            str = '',
            data = {
                page: currentPage
            };
        jQuery.extend(data, extraData);

        $.ajax({
            type: jQuery.url.BasicInformationManagement.userList.type,
            url: jQuery.url.BasicInformationManagement.userList.url,
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            data: data,     //JSON.stringify
            dataType: "json",
            success: function (rs) {
                $('#J_template').empty();
                if( rs.code == 0){
                    $('#pageLimit').bootstrapPaginator({
                        totalPages: rs.pageDataCount
                    });
                    $.each(rs.list, function(index, item){
                        str += '<tr data-id="'+ item.id +'" data-name="'+ item.name +'" data-number="'+ item.number +'" data-sex="'+ item.sex +'" data-phoneNumber="'+ item.phoneNumber +'" data-type="'+ item.type +'" data-gradeId="'+ item.gradeId +'" data-subjectId="'+ item.subjectId +'" data-gradeIdList="'+ item.gradeIdList +'">\
                                <td><input type="checkbox" name="subChk"/></td>\
                                <td>'+ item.serialNumber +'</td>\
                                <td>'+ item.name +'</td>\
                                <td>'+ item.number +'</td>\
                                <td>'+ item.sex +'</td>\
                                <td>'+ item.phoneNumber +'</td>\
                                <td>'+ item.type +'</td>\
                                <td>'+ item.gradeId +'</td>\
                                <td>'+ item.subjectId +'</td>\
                                <td>\
                                    <a href="#?id=' + item.id + '" class="label-info J_modify"><i class="fa fa-pencil"></i>&nbsp;修改</a>\
                                </td>\
                            </tr>'
                    }); 
                    $('#J_template').append(str);
                }else{                
                    Alert('提示信息', '操作失败，返回参数不正确!');
                }

            },
            error: function (message) {
                Alert("提示信息", "请求发送失败。")
            }
        });
    };

    /**
     * 修改框更改角色事件
     * @param  {[type]} e){                 } [description]
     * @return {[type]}      [description]
     */
    function changeEditRole(){
        if($('.J_editForm').find("input:radio[name='type']:checked").val() == 1){
            $(".J_course").removeClass('hidden');
        }else if($('.J_editForm').find("input:radio[name='type']:checked").val() == 2){
            $(".J_course").addClass('hidden');
        }
    };

    /**
     * 新增框更改角色事件
     * @param  {[type]} e){                 } [description]
     * @return {[type]}      [description]
     */
    function changeAddRole(){
        if($('.J_addForm').find("input:radio[name='type']:checked").val() == 1){
            $(".J_course").removeClass('hidden');
        }else if($('.J_addForm').find("input:radio[name='type']:checked").val() == 2){
            $(".J_course").addClass('hidden');
        }else{
            $(".J_course").addClass('hidden');
        }
    };


    /**
     * 列表修改实现
     * @param  {[type]} e){                 } [description]
     * @return {[type]}      [description]
     */
    function modifyInfo(e){
        var
            tr = $(e.target).parents('tr'),
            id = $(tr).attr('data-id'),
            name = $(tr).attr('data-name'),
            userId = $(tr).attr('data-number'),
            sex = $(tr).attr('data-sex'),
            phoneNum = $(tr).attr('data-phoneNumber'),
            userRole = $(tr).attr('data-type'),
            // userGrade = $(tr).attr('data-gradeId'),
            userCourse = $(tr).attr('data-subjectId'),
            // gradeIdList = $(tr).attr('data-gradeIdList');
            gradeIdList = $(tr).attr('data-gradeId').split(' '),
            liList = $('.J_editGrade').next().find('li'),
            editcourseLi = $('.J_editCourse').next().find('li'),
            inputValue =[],
            courseLiInputValue = [];

        $('.hidId').val(id);
        $('.J_editName').val(name);
        $('.J_editNum').val(userId);
        $('.J_editPhoneNum').val(phoneNum);
        if(sex == '男'){
            $('.J_editRadio1').prop('checked', true);
        }else{
            $('.J_editRadio2').prop('checked', true);
        };
        if(userRole == '老师'){
            $('.J_editRadio3').prop('checked', true);
        }else{
            $('.J_editRadio4').prop('checked', true);
        };
        
        for (var j = 0; j < gradeIdList.length; j++) {
            liList.each(function(index, el) {
                var label = $(this).find('label');
                if($.trim(gradeIdList[j]) == $.trim(label.text())){
                    // $(label).children().prop('checked', true); 
                    inputValue.push(label.children('input').val());
                    
                }

            });
        };
         $('#editGrade').multiselect('select', inputValue);

        editcourseLi.each(function(ind, ite) {
            var label = $(this).find('label');
            if($.trim(userCourse) == $.trim(label.text())){
                // $(label).children().prop('checked', true); 
                courseLiInputValue.push(label.children('input').val());
               
            }
        });
        $('#editCourse').val('').multiselect("refresh");
         $('#editCourse').multiselect('select', courseLiInputValue);

    };
    
    /**
     * 对话框编辑按钮
     * @param  {[type]} e){                 } [description]
     * @return {[type]}      [description]
     */
    $('.J_editDlg').click(function(e){
        var 
            data = $('.J_editForm').data('bootstrapValidator');
        if (data) {
        // 修复记忆的组件不验证
            data.validate();

            if (!data.isValid()) {
                return false;
            }
        }
        edit(e);
    });

   

    /**
     * 编辑事件
     */
    function edit(e){
        var
            page = $('#pageLimit li.active').text(),
            id = $('.hidId').val(),
            editname = $('.J_editForm').find("input[name='name']").val(),
            editnumber = $('.J_editForm').find("input[name='number']").val(),
            editsex = $('.J_editForm').find("input:radio[name='sex']:checked").val(),
            editphoneNum = $('.J_editForm').find("input[name='phoneNumber']").val(),
            editrole = $('.J_editForm').find("input:radio[name='type']:checked").val(),
            // editgrade = $('.J_editForm').find("input[name='grade']").val(),
            // editcourse = $('.J_editForm').find("input[name='course']").val(),
            // editgrade = $('#editGrade').val(),
            editgrade = [],
            editcourse = $('.J_editCourse').val(),
            form = {};

            //取得年级选择列表
            $(".J_editGrade option:selected").each(function () {  
                editgrade.push($(this).val());  
            });  

            if(editgrade.length >0){
                editgrade = editgrade.toString();
            }else{
                editgrade = '0';
            }


            form = {
                'name': editname,
                'number': editnumber,
                'sex': editsex,
                'phoneNumber': editphoneNum,
                'type': editrole,
                'gradeId':editgrade,
                'subjectId': editcourse
            }

        jQuery.extend(form, {
            id: id
        });
        $.ajax({
            type: jQuery.url.BasicInformationManagement.editForm.type,
            url: jQuery.url.BasicInformationManagement.editForm.url,
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            data: form,     //JSON.stringify
            dataType: "json",
            success: function (rs) {
                $('#editDialog').modal('hide');
                if( rs.code == 0){
                    window.location.reload();
                    Pagination(page);
                    Alert('提示信息','编辑成功!');
                }else{                
                    Alert('提示信息', '操作失败，返回参数错误!');
                }
            },
            error: function (message) {
                $('#editDialog').modal('hide'); 
                Alert('提示信息', '操作失败，请求失败!');
            } 
        });
    };

    /**
     * 关闭编辑对话框清除校验
     * @param  {[type]} ) {                       } [description]
     * @return {[type]}   [description]
     */
    $('#editDialog').on('hidden.bs.modal', function() {
        $('#editGrade').val('').multiselect("refresh");
        $('#editCourse').val('').multiselect("refresh");
        $('.J_editForm').bootstrapValidator('resetForm', true);
        $('.J_editForm').data('bootstrapValidator').resetForm();
        $('.J_editForm').data('bootstrapValidator', null);
        formValidatorEditForm();
    });

    /**
     * 编辑框验证
     */
    function formValidatorEditForm(){
        $('.J_editForm').bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                name: {
                    validators: {
                        notEmpty: {
                            message: '姓名不能为空'
                        }
                    }
                },
                number: {
                    validators: {
                        notEmpty: {
                            message: '学号/工号不能为空'
                        },
                        numeric: {
                            message: '学号/工号只能是数字'
                        }
                    }
                },
                phoneNumber:{
                    validators: {
                        stringlength: {
                            min:11,
                            max:11,
                            message:'请输入11位手机号码'
                        },
                        regexp: {
                            regexp: /^1\d{10}$/,
                            message: '请输入正确的手机号码'
                        }
                    }
                }
            }
        });
    };

    /**
     * 列表新增实现
     * @param  {[type]} e){                 } [description]
     * @return {[type]}      [description]
     */
    $('.J_addDlg').click(function(){
            var 
                data = $('.J_addForm').data('bootstrapValidator');
            if (data) {
            // 修复记忆的组件不验证
                data.validate();

                if (!data.isValid()) {
                    return false;
                }
            }
            add();
        });
    /**
     * 新增事件
     */
    function add(){
        var
            addname = $('.J_addForm').find("input[name='name']").val(),
            addnumber = $('.J_addForm').find("input[name='number']").val(),
            addsex = $('.J_addForm').find("input:radio[name='sex']:checked").val(),
            addphoneNum = $('.J_addForm').find("input[name='phoneNumber']").val(),
            addrole = $('.J_addForm').find("input:radio[name='type']:checked").val(),
            addgrades = $('#addGrade').val(),
            addgrade ,
            addcourse = $('.J_addCourse').val(),
            form;

            if(addgrades && addgrades.length >0){
                addgrade = ($('#addGrade').val()).toString();
            }else{
                addgrade = '0';
            }
            
            form = {
                'name': addname,
                'number': addnumber,
                'sex': addsex,
                'phoneNumber': addphoneNum,
                'type': addrole,
                'gradeId': addgrade,
                'subjectId': addcourse
            };
        // $('select[id="grade"]:checked').each(function(){
        //     addgrade.push($(this).val());
        // });
        // jQuery.extend(form, {grade: addgrade});
        $.ajax({
            type: jQuery.url.BasicInformationManagement.addForm.type,
            url: jQuery.url.BasicInformationManagement.addForm.url,
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            data: form,     //JSON.stringify
            dataType: "json",
            success: function (rs) {
                $('#addDialog').modal('hide');
                if( rs.code == 0){
                    window.location.reload();                   
                    Alert('提示信息', '添加成功!');
                }else{                
                    Alert('提示信息', '操作失败，返回参数错误!');
                }
            },
            error: function (message) {
                $('#addDialog').modal('hide');
                Alert('提示信息', '操作失败，请求失败!');
            }
        });
    };

    /**
     * 关闭新增对话框清除校验
     * @param  {[type]} ) {                       } [description]
     * @return {[type]}   [description]
     */
    $('#addDialog').on('hidden.bs.modal', function() {
        changeAddRole();
        $('.J_addName').val('');
        $('.J_addNum').val('');
        $('.J_addPhoneNum').val('');
        $('.J_addCourse').val(0);
        $('#addGrade').val('').multiselect("refresh");
        $('input:radio[name="sex"]').prop("checked", false);
        $('input:radio[name="type"]').prop("checked", false);
        $('.J_addForm').bootstrapValidator('resetForm', true);
        $('.J_addForm').data('bootstrapValidator').destroy();
        $('.J_addForm').data('bootstrapValidator', null);
        formValidatorAddForm();
    });
    /**
     * 新增框验证
     */
    function formValidatorAddForm(){
        $('.J_addForm').bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                name: {
                    validators: {
                        notEmpty: {
                            message: '姓名不能为空'
                        }
                    }
                },
                number: {
                    validators: {
                        notEmpty: {
                            message: '学号/工号不能为空'
                        },
                        numeric: {
                            message: '学号/工号只能是数字'
                        }
                    }
                },
                phoneNumber:{
                    validators: {
                        stringlength: {
                            min:11,
                            max:11,
                            message:'请输入11位手机号码'
                        },
                        regexp: {
                            regexp: /^1\d{10}$/,
                            message: '请输入正确的手机号码'
                        }
                    }
                }
            }
        });
    };
    /**
     * 批量删除实现
     * @param  {[type]} e){                 } [descripti on]
     * @return {[type]}      [description]
     */
    function delAll(){
        // 判断是否至少选择一项 
        var 
            checkedList = [],
            checkedNum = $("input[name='subChk']:checked").length,
            id;

        $("input[name='subChk']:checked").each(function() {
            checkedList.push($(this).parents('tr').attr('data-id'));
        }); 
        

        if(checkedNum == 0) { 
            Alert('提示信息', '请至少选择一项!');  
        }else{// 批量选择 
            Confirm('提示信息', '确定删除所选人员吗？', function(){
                $.ajax({ 
                    type: jQuery.url.BasicInformationManagement.delAllInfo.type, 
                    url: jQuery.url.BasicInformationManagement.delAllInfo.url,
                    contentType: "application/x-www-form-urlencoded; charset=utf-8",
                    data: {delitems:checkedList.toString()},
                    dataType: "json",
                    success: function(rs){
                        if(rs.code == 0){
                            $("[name ='subChk']:checkbox").attr("checked", false);
                            $(".J_allChk").prop("checked", false);
                            window.location.reload();
                        }else{
                            Alert('提示信息', '操作失败，返回参数不正确!');
                        }  
                    },
                    error: function (message) {
                       Alert("提示信息", "请求发送失败。")
                        $(".J_allChk").prop("checked", false);
                    } 
                }); 
            });
        }
    };

    /**
     * 批量导出按钮
     * @param  {[type]} e){                 } [description]
     * @return {[type]}      [description]
     */
    $(".J_allDown").click(function() {
        var 
            checkedList = [],
            checkedNum = $("input[name='subChk']:checked").length; 

        $("input[name='subChk']:checked").each(function() { 
            checkedList.push($(this).parents('tr').attr('data-id')); 
        }); 

        if(checkedNum == 0) { // 判断是否至少选择一项 
            Alert('提示信息', '请至少选择一项!');  
        }else{// 批量选择
            Confirm('提示信息', '确定导出所选人员吗？', function(){
                checkedList = checkedList.toString();
                window.location ='export/'+checkedList; 
            });
        } 
    }); 

    /**
     * 批量导入
     */
    $(".J_import").click(function() {
        if(filterFile()){
            if($('.uploading').length == 0){
               $(".modal-body").append("<span class='uploading'>正在上传...</span>");
               $(".modal-footer").addClass("hidden");
            }
            fileUpload();
        }
    });
    /**
     * 上传文件
     * @return {[type]} [description]
     */
    function fileUpload(){
        // if( filterFile() ){
            $.ajaxFileUpload({
                url: jQuery.url.BasicInformationManagement.upAllInfo.url,
                contentType: "application/x-www-form-urlencoded; charset=utf-8",
                secureuri: false,
                fileElementId: 'fileToUpload', //文件选择框的id属性
                dataType : "text/html",//服务器返回的格式，可以是json
                //相当于java中try语句块的用法
                success: function (data) {
                    //关闭遮盖层
                    
                    data = JSON.parse(data);
                    if(data.code == 0){
                        $("#exportDialog").modal('hide');
                        Confirm("提示信息", data.errMsg,function(){
                            window.location.reload();
                        })
                    }else{
                        // Alert("提示信息", data.errMsg);
                    }
                },
                error: function () {
                    // Alert("提示信息","导入出错!" );
                }
            });
        // }
    }
    /**
     * 限制上传文件格式
     */
    function filterFile(){
        var
            filepath = $("#fileToUpload").val(),
            extStart = filepath.lastIndexOf("."),
            ext = filepath.substring(extStart, filepath.length).toUpperCase();

        if (ext != ".XLS" && ext != ".XLSX") {
            Alert("提示信息", "文件格式不正确");
            $("#fileToUpload").val("");
            return false;
        }
        return true;
    }

    
});

